package com.sd.repay.realm;

import com.alibaba.fastjson.JSONObject;
import com.sd.repay.common.CommonResult;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class ClientLoginFormAuthenticationFilter extends FormAuthenticationFilter {
    private static final Logger log = LoggerFactory.getLogger(ClientLoginFormAuthenticationFilter.class);

    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        WebUtils.issueRedirect(request, response, getSuccessUrl(), null, true);
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if (!this.isLoginRequest(request, response)) {//是否是登录请求，loginUrl
            String fullContentType = "application/json;charset=UTF8";
            response.setCharacterEncoding("UTF-8");
            response.setContentType(fullContentType);
            response.getWriter().print(JSONObject.toJSONString(CommonResult.build(403, "请登录后重试")));
            log.warn("请登录后重试");
            return false;
        }
        return true;
    }

}
